package com.pioneer.app.sms.timeTask;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.app.util.DateTimeUtil;
import com.pioneer.app.sms.define.TypeDefine;
import com.pioneer.app.sms.define.TypeDefineDAO;

public class MessageMg implements ServletContextListener  {
	private static Timer timer = null;

	private static Map tasks=new HashMap();
  public void contextInitialized(ServletContextEvent event) {
     timer = new Timer(true);
     loadTask();
     this.timer.schedule(new UpSmsTask(), 10, 1000*60);
   }
  
  
  public void contextDestroyed(ServletContextEvent event) {
     timer.cancel();
   }
  
  public static void addTask(TypeDefine define){
  	SMSTask task=new SMSTask();
		task.setTypeDef(define);
		addTask(task);
  }
  
  public void addTmpTask(SMSTask task){
  	timer.schedule(task, task.getSendDate());
  }
  private static void addTask(SMSTask task){
  	
  	
  	TypeDefine typedef=task.getTypeDef();
  	SMSTask runtask=(SMSTask)tasks.get(typedef.getId());
		try{
			runtask.cancel();
		}catch(Exception e){}
		
  	 if("开启".equalsIgnoreCase(typedef.getStatus().trim())){
//  		加入一个启动事务
  		String startDateStr=typedef.getStartDate();
  		
  	  try {
				Date startDate=DateTimeUtil.parse(startDateStr, "yyyy-MM-dd HH:mm:ss");
				long datelong=DateTimeUtil.diffTimes(startDate, new Date());
				if(datelong<0)
					startDate=new Date();
				startDate.setTime(startDate.getTime()+10);
				timer.schedule(task, startDate, typedef.getLoopType().intValue());
			} catch (RuntimeException e) {
				System.out.println("定时发送短信加载失败！");
				System.out.println("name="+typedef.getTypeName());
				System.out.println("开始时间="+typedef.getStartDate());
				System.out.println("循环时间="+typedef.getLoopType());
				e.printStackTrace();
			}
  	}
  	tasks.put(task.getTypeDef().getId(), task);
		
  }
  
  private void loadTask(){
  	TypeDefineDAO dao=new TypeDefineDAO();
  	List taskDefs=dao.findByCondition(null);
  	if(null!=taskDefs){
  		TypeDefine type=null;
  		Iterator it=taskDefs.iterator();
  		while(it.hasNext()){
  			type=(TypeDefine)it.next();
  			SMSTask task=new SMSTask();
  			task.setTypeDef(type);
  			addTask(task);
  		}
  	}
  }

  private static MessageMg _mg=new MessageMg();

  public static MessageMg getInst(){
  	return _mg;
  }
  public static void main(String[]args){
  	String startDateStr="2008-12-04 16:20:11";
  	Date startDate=DateTimeUtil.parse(startDateStr, "yyyy-MM-dd HH:mm:ss");
		long datelong=DateTimeUtil.diffTimes(startDate, new Date());
		System.out.println("datelong="+datelong);
  }
}


